
package com.xbongbong.paas.log.entity;

import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.NetAddressUtil;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 * 登录日志实体,对应mongodb表
 * @author kaka
 * @date 2019/1/18 10:20
 * @since v1.0
 * @version v1.0
 */
@Data
@Document(collection = "login_log")
public class LoginLogEntity implements Serializable {

	private static final long serialVersionUID = -1908544046021344687L;

	private static final Logger LOG = LoggerFactory.getLogger(LoginLogEntity.class);

	/**
	 * 主键ID
	 */
	@Id
	private String id;

	/**
	 * 公司ID
	 */
	private String corpid;

	/**
	 * 操作人员工ID
	 */
	private String userId;

	/**
	 * 操作人员工姓名
	 */
	private String userName;

	/**
	 * 根据不同平台操作分别取以下值：android, ios, web, dingtalk, all
	 */
	private String platform;

	/**
	 * 浏览器信息，记录浏览器内核相关信息
	 */
	private String browserInfo;

	/**
	 * 操作者IP，api端可以不用处理该参数，设为空字符串
	 */
	private String ip;

	/**
	 * 备注信息
	 */
	private String memo;

	/**
	 * 操作时间
	 */
	private Integer addTime;

	public LoginLogEntity(){
		this.addTime = DateUtil.getInt();
		this.memo = "";
	}

	/**
	 * 登录日志构造方法
	 * @param corpid 公司corpid
	 * @param userId 登录员工userId
	 * @param userName 登录员工姓名
	 * @param platform 登录平台
	 * @param browserInfo 登录设备浏览器信息
	 * @param ip 登录ip
	 */
	public LoginLogEntity(String corpid, String userId, String userName, String platform,
						  String browserInfo, String ip) {
		this();
		this.corpid = corpid;
		this.userId = userId;
		this.userName = userName;
		this.platform = platform;
		this.browserInfo = browserInfo;
		this.ip = ip;
	}

	public LoginLogEntity(String corpid, String userId, String userName, String platform,
						  HttpServletRequest request) {
		this();
		this.corpid = corpid;
		this.userId = userId;
		this.userName = userName;
		this.platform = platform;
		String userAgent = request == null ? "" : request.getHeader("user-agent");
		String ip = "";
		try {
			ip  = NetAddressUtil.getIpAddr(request);
		} catch (Exception e) {
			LOG.error("获取ip地址出错 : ", e);
		}
		this.browserInfo = userAgent;
		this.ip = ip;
	}

	/**
	 * 登录日志构造方法
	 * @param baseDTO 一般传入的是baseDTO的子类
	 */
	public LoginLogEntity(BaseDTO baseDTO) {
		this();
		this.corpid = baseDTO.getCorpid();
		this.userId = baseDTO.getUserId();
		this.userName = baseDTO.getLoginUserName();
		this.platform = baseDTO.getPlatform();
		this.browserInfo = baseDTO.getBrowserInfo();
		this.ip = baseDTO.getIp();
	}
}

